const fs = require('fs'),
	logger = require('log4js').getLogger()

var lastTime = 0
var lastDevices = {}

module.exports = (req, res) => {
	require('../util/service').handleGet(req, res, (reqObj, resolve) => {
		var content = fs.readFileSync('/proc/net/dev', 'utf8')
		var nowDevices = {}
		content.split('\n').forEach(item => {
		    var obj = []
		    item.split(/\s+/).forEach(_item => {
		        if (_item)
		            obj.push(_item)
		    })
		    if (obj.length == 0)
		    	return
		    obj[0] = obj[0].substring(0, obj[0].length - 1)
		    nowDevices[obj[0]] = {
		    	in: obj[1],
		    	out: obj[9]
		    }
		})

		var nowTime = new Date().getTime()
		var deltaTime = nowTime - lastTime
		var result = []
		reqObj.device.split(',').forEach(item => {
			if (lastDevices[item] && nowDevices[item] && lastTime) {
				result.push({
					device: item,
			   		in: (nowDevices[item].in - lastDevices[item].in) / deltaTime * 1000,
			  		out: (nowDevices[item].out - lastDevices[item].out) / deltaTime * 1000
				})
			}
		})
		resolve(result)

		lastDevices = nowDevices
		lastTime = nowTime
	})
}